package com.snowfield.lbcommon.utils.security;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.Key;

/**
 * 实现了DES加密解密
 *
 * @author snowfield
 * @date 2024-07-10
 */
public class DesUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(DesUtils.class);

    //保存密钥KEY
    private static final String DESKEY_PATH = "/usr/local/snowfield/desKey.bin";
    //密钥KEY
    private static Key desKey;

    static {
        initKey();
    }

    private static void initKey() {
        try {
            if (desKey == null) {
                File keyFile = new File(DESKEY_PATH);
                if (!keyFile.exists()) {
                    // 密钥文件不存在,生成此文件,并把生成的密钥key写入文件
                    keyFile.createNewFile();
                    KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
                    desKey = keyGenerator.generateKey();
                    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(keyFile));
                    out.writeObject(desKey);
                    out.close();
                } else {
                    // 密钥文件存在,从密钥文件中读取密钥key
                    ObjectInputStream in = new ObjectInputStream(new FileInputStream(keyFile));
                    try {
                        // 转换文件内容为Key对象
                        desKey = (Key) in.readObject();
                    } catch (Exception e) {
                        // 如果出现转换的异常,则重新生成一个key,并写入文件中
                        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
                        desKey = keyGenerator.generateKey();
                        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(keyFile));
                        out.writeObject(desKey);
                        out.close();
                    } finally {
                        in.close();
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }

    /**
     * 使用des算法加密
     *
     * @param text 明文
     * @return 密文
     */
    public static String encryptByDesKey(String text) {
        try {
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            byte[] result = cipher.doFinal(Base64.encodeBase64(StringUtils.getBytes(text, StandardCharsets.UTF_8)));

            return Base64.encodeBase64String(result);
        } catch (Exception e) {
            LOGGER.error("", e);
        }

        return "";
    }

    /**
     * 使用des算法解密
     *
     * @param text 密文
     * @return 明文
     */
    public static String decryptByDesKey(String text) {
        try {
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            byte[] result = cipher.doFinal(Base64.decodeBase64(StringUtils.getBytes(text, StandardCharsets.UTF_8)));

            return new String(Base64.decodeBase64(result));
        } catch (Exception e) {
            LOGGER.error("", e);
        }

        return "";
    }
}
